from rest_framework import viewsets, mixins
from rest_framework.decorators import list_route
from rest_framework.response import Response

from carts.models import CartModel
from carts.serializers import CartSerializer
from utils.authentication import UserAuthentication


class CartView(viewsets.GenericViewSet,
               mixins.ListModelMixin,
               mixins.UpdateModelMixin):

    queryset = CartModel.objects.all()

    serializer_class = CartSerializer

    authentication_classes = (UserAuthentication,)

    def total_price(self, request):
        user = request.user
        # 查询当前用户在购物车中商品为勾选状态的数据
        carts = self.get_queryset().filter(user=user, is_select=True)
        total = 0
        for cart in carts:
            total += cart.goods.marketprice * cart.c_num
        return total

    def list(self, request, *args, **kwargs):
        # 重构list方法，组装结果
        # {‘code’:200, 'msg': '', 'data':{'carts':'', 'total_price':''}}
        user = request.user
        # CartModel.objects.filter(user=user).all()
        carts = self.get_queryset().filter(user=user)
        serializer = self.get_serializer(carts, many=True)
        res = {
            'carts': serializer.data,
            'total_price': self.total_price(request)
        }
        return Response(res)


    @list_route(methods=['POST'])
    def add_cart(self, request):
        # 接收token和goodsid
        user = request.user
        goodsid = request.data.get('goodsid')
        # 判断该登录用户是否已添加该商品
        # 如果没有，则新建。如果有，则修改数量
        cart_goods = CartModel.objects.filter(user=user,
                                              goods_id=goodsid).first()
        if cart_goods:
            # 购物车已有值，则修改数量
            cart_goods.c_num += 1
            cart_goods.save()
        else:
            # 购物车没有信息，则新建
            CartModel.objects.create(user=user, goods_id=goodsid)
        res = {
            'msg': '添加商品成功'
        }
        return Response(res)

    @list_route(methods=['POST'])
    def sub_cart(self, request):
        user = request.user
        goods_id = request.data.get('goodsid')
        # cart_goods = CartModel.objects.filter(user=user,
        #                                       goods_id=goods_id).all()
        # self.queryset.filter(user=user, goods_id=goods_id).first()
        cart_goods = self.get_queryset().filter(user=user,
                                                goods_id=goods_id).first()
        if cart_goods.c_num > 1:
            # 商品数量大于1，则之间1
            cart_goods.c_num -= 1
            cart_goods.save()
        else:
            # 商品数量小于等于1，则删除
            cart_goods.delete()
        res = {
            'msg': '减少商品成功'
        }
        return Response(res)

    def update(self, request, *args, **kwargs):
        # 更新商品的选择状态
        # pk = kwargs.get('pk')
        # instance = CartModel.objects.get(pk=pk)
        instance = self.get_object()
        instance.is_select = not instance.is_select
        instance.save()
        res = {
            'msg': '更新商品选择状态成功'
        }
        return Response(res)